package controllers

import (
	"aa/cache"
	"aa/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"time"
)

type Petcontrollers struct {
	beego.Controller
}

func (c *Petcontrollers) Add() {
	name := c.GetString("name")
	pe := models.As{
		Name: name,
	}
	models.DB.Create(&pe)
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
}
func (c *Petcontrollers) Upload() {
	name := c.GetString("name")
	address := c.GetString("address")
	img := c.GetString("img")
	AsId, _ := c.GetInt("as_id")
	file, header, err := c.GetFile("img")

	if header.Size > 2*1024*1024 {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "文件过大上传失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	if filepath.Ext(header.Filename) != ".jpg" || filepath.Ext(header.Filename) != ".png" {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "文件格式不对",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	pets := models.Pet{
		Name:    name,
		Address: address,
		Img:     img,
		AsId:    AsId,
	}
	err = models.DB.Create(&pets).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "上传成功",
			Data: "127.0.0.1:8080" + path,
		}
		c.ServeJSON()
	}
}
func (c *Petcontrollers) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	query := models.DB.Model(&models.Pet{})
	if name == "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	offset := (page - 1) * size
	var count int64
	query.Count(&count)
	var ptt []models.Pet
	query.Preload("As").Limit(size).Offset(offset).Find(&ptt)
	key := "plist"
	res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if res != "" {
		json.Unmarshal([]byte(res), &ptt)
	} else {
		jsonData, _ := json.Marshal(&ptt)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*2)

	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: ptt,
	}
	c.ServeJSON()
}
func (c *Petcontrollers) Show() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	var pt models.Pet
	models.DB.Where("id =?", id).Find(&pt)
	key := "show_p"
	res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if res != "" {
		json.Unmarshal([]byte(res), &pt)
	} else {

		jsonData, _ := json.Marshal(&pt)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*2)
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: pt,
	}
	c.ServeJSON()

}
